package com.shawny;

import com.shawny.model.Action;
import com.shawny.model.Game;
import com.shawny.model.Notification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.security.Principal;

/**
 * Created by Shawn Wong on 2017/3/30.
 * Try you best !
 */
@Controller
public class GameController {
    private static int SIZE = 3;
    private Game game;


    @Autowired
    private SimpMessagingTemplate template;

    @GetMapping("/page")
    public String page() {
        return "game";
    }

    public GameController() {
        Game game = new Game();
        game.setController(this);
        this.game = game;
    }


    @MessageMapping("/game")
    public void handleActionRequest(Action action, Principal pr) {
        action.setPlayerId(pr.getName());
        if (action.getName().equals("join")) {
            game.join(action);
        } else if (action.getName().equals("ready")) {
            game.setReady(action);
        } else if (action.getName().equals("click")) {
            game.onClick(action);
        }

    }


    public void sendToUser(Notification notification) {

        template.convertAndSendToUser(notification.getPlayerId(), "/topic/game", notification);

    }

    public void broadcast(Notification notification) {

        template.convertAndSend("/topic/game", notification);
    }




}
